<template>
  <div>
    <el-dialog
      top="5vh"
      width="55%"
      :title="title"
      destroy-on-close
      append-to-body
      fullscreen
      v-if="visible"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="handleEditReset"
    >
      <div class="dialog-content">
        <avue-form ref="editForm" :option="option" @submit="handSaveConfig" v-model="form">
          <template slot="planCode">
            <el-input placeholder="请输入编码" v-model="form.planCode" disabled> </el-input>
          </template>
          <template slot-scope="{}" slot="avueCurd">
            <avue-crud
              ref="editCrud"
              v-model="curdForm"
              :option="tableOption"
              :data="form.qmsInspectionPlanObjectVOList"
              :permission="permissionList"
              @row-update="rowUpdate"
              @row-save="rowSave"
              @row-del="rowDel"
              :before-open="beforeOpen"
              @search-change="searchChange"
              @search-reset="searchReset"
            >
            </avue-crud>
          </template>
          <template slot-scope="{}" slot="ruleControl">
            <label>备注：自动报检的触发时机在【参数管理】中进行配置</label>
          </template>
          <template slot-scope="{}" slot="omissionControl">
            <h3>1. 防漏检验控制：</h3>
            <div class="ml20">
              <el-radio v-model="form.missingInspectControl" :true-label="1" :false-label="0">
                <el-tooltip content="在预警中心设置若待检单的未处理时长达到设定值时，则会预警消息通知！" placement="top">
                  <i class="el-tooltip el-icon-info"></i>
                </el-tooltip>
                允许生产，仅预警提示告知
              </el-radio>
              <!-- <el-radio v-model="form.missingInspectControl" :label="1">
                <el-tooltip content="在预警中心设置若待检单的未处理时长达到设定值时，则会预警消息通知！" placement="top">
                  <i class="el-tooltip el-icon-info"></i>
                </el-tooltip>
                允许生产，仅预警提示告知
              </el-radio> -->
              <span>备注：具体到预警中心设计</span>
            </div>
          </template>
        </avue-form>
      </div>
      <div slot="footer">
        <el-button size="small" type="primary" icon="el-icon-check" @click="handleEditSubmit">保存</el-button>
        <el-button size="small" icon="el-icon-delete" @click="handleEditReset">取消</el-button>
      </div>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="dialogOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </div>
</template>

<script>
import { guid } from '@/util/helpers';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { getPlanConfigDetail, savePlanConfig } from '@/api/quality/palnConfig';
import { filterEmptyValues } from '@/util/util';
export default {
  name: 'editProcessPlanConfig',
  components: {
    commonModalTemplate
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '编辑'
    },
    dialogType: {
      type: String,
      default: 'add'
    }
  },
  watch: {
    // title(val) {
    //   if (val !== '编辑') {
    //     this.updateCode();
    //   }
    //   }
    // }
    'form.inspectSubType'(nval, olval) {
      if (nval && olval && nval !== olval) {
        this.form.qmsInspectionPlanObjectVOList = [];
      }
    }
  },
  data() {
    return {
      dialogOption: {},
      timer: new Date().getTime(),
      modalName: '',
      curdForm: {},
      showImportDialog: false,
      option: {
        searchShow: true,
        searchMenuSpan: 6,
        menuPosition: 'right',
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 150,
        group: [
          {
            label: '基础信息',
            prop: 'equipmentInfo',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '计划名称',
                prop: 'planName',
                span: 6,
                rules: [{ required: true, message: '请输入计划名称', trigger: 'blur' }]
              },
              {
                label: '计划编码',
                prop: 'planCode',
                disabled: true,
                placeholder: '系统自动生成',
                span: 6
              },
              {
                label: '检验类型',
                prop: 'planType',
                value: '制程巡检',
                disabled: true,
                span: 6
              },
              {
                label: '巡检类型',
                span: 6,
                prop: 'inspectSubType',
                labelTip: '具体到预警中心设计',
                type: 'select',
                dicUrl: '/api/blade-system/dict/dictionary?code=ipqc_type',
                rules: [{ required: true, message: '请选择巡检类型', trigger: 'change' }],
                props: {
                  label: 'dictValue',
                  value: 'dictKey'
                }
              }
            ]
          },
          {
            label: '巡检对象',
            prop: 'equipmentInfo1',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                prop: 'avueCurd',
                labelWidth: 0,
                span: 24,
                order: 6,
                formslot: true
              }
            ]
          },
          {
            label: '报检方式',
            prop: 'equipmentInfo2',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '报检方式',
                prop: 'sendExamineType',
                dicData: [
                  { label: '自动', value: 'AUTO' },
                  { label: '手动', value: 'MANUAL' }
                ],
                multiple: true,
                span: 8,
                labelTip: '选择手动或自动后，则表示生成的待检单会受防呆规则内容的受控',
                type: 'select',
                rules: [{ required: true, message: '请选择报检方式', trigger: 'change' }]
              },
              {
                prop: 'ruleControl',
                labelWidth: 0,
                span: 8,
                formslot: true
              }
            ]
          },
          {
            label: '防呆规则',
            prop: 'equipmentInfo2',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                prop: 'omissionControl',
                labelWidth: 0,
                span: 24,
                order: 6,
                formslot: true
              }
            ]
          },
          {
            label: '关闭控制',
            prop: 'equipmentInfo4',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '未检时间(min)',
                type: 'number',
                min: 0,
                precision: 0,
                prop: 'closeInspectDuration',
                labelWidth: 150,
                span: 10,
                labelTip: '待检单超过设定的未检时间时，则该待检单会强制关闭；状态由待检变为超期关闭',
                rules: [{ required: true, message: '请输入未检时间', trigger: 'blur' }]
              }
            ]
          }
        ]
      },
      form: {
        planType: '制程巡检'
      },
      selectRow: [],
      tableOption: {
        height: '400px',
        calcHeight: 30,
        tip: false,
        searchShow: false,
        filterBtn: false,
        refreshBtn: false,
        columnBtn: false,
        border: true,
        index: true,
        indexLabel: '序号',
        searchMenuSpan: 4,
        searchLabelWidth: 90,
        viewBtn: false,
        delBtn: true,
        editBtn: true,
        addBtn: true,
        addBtnText: '新增巡检范围',
        labelWidth: 130,
        selection: false,
        highlightCurrentRow: true, // 选中高亮
        dialogClickModal: false,
        searchMenuPosition: 'right',
        searchSpan: 6,
        column: [
          {
            label: '巡检类型',
            span: 8,
            prop: 'inspectSubType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=ipqc_type',
            rules: [{ required: true, message: '请选择巡检类型', trigger: 'change' }],
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            disabled: true,
            // change: ({ value }) => {
            //   if (!this.isFirstInit) {
            //     this.curdForm = {
            //       inspectSubType: value,
            //       workshopName: '',
            //       workshopId: '',
            //       lineName: '',
            //       lineId: '',
            //       ipqcTimeframeId: '',
            //       remark: ''
            //     };
            //   }
            //   this.isFirstInit = false;
            // },
            control: (val, form) => {
              if (val === 'WORKSHOP') {
                return {
                  lineName: {
                    display: false
                  },
                  workshopName: {
                    display: true,
                    rules: [{ required: true, message: '请选择车间', trigger: 'blur' }]
                  }
                };
              }
              if (val === 'LINE') {
                return {
                  lineName: {
                    display: true,
                    rules: [{ required: true, message: '请选择产线', trigger: 'blur' }]
                  },
                  workshopName: {
                    display: true,
                    rules: []
                  }
                };
              } else {
                return {
                  lineName: {
                    display: false
                  },
                  workshopName: {
                    display: false
                  }
                };
              }
            }
          },
          {
            label: '车间',
            span: 8,
            prop: 'workshopName',
            type: 'search',
            disabled: true,
            appendClick: () => {
              this.openWorkshop();
            }
          },
          {
            label: '产线',
            prop: 'lineName',
            type: 'search',
            disabled: true,
            span: 8,
            search: true,
            appendClick: () => {
              this.openProductionLine();
            }
          },
          // {
          //   label: '工段',
          //   prop: 'sectionName',
          //   disabled: true,
          //   type: 'search',
          //   appendClick: () => {
          //     this.openWorkshopSection();
          //   }
          // },
          // {
          //   label: '巡检时段',
          //   prop: 'times',
          //   searchOrder: 1,
          //   searchType: 'timerange',
          //   type: 'timerange',
          //   searchSpan: 6,
          //   hide: true,
          //   format: 'HH:mm',
          //   valueFormat: 'HH:mm',
          //   startPlaceholder: '巡检时段开始范围自定义',
          //   endPlaceholder: '巡检时段结束范围自定义'
          // },
          {
            label: '巡检时段',
            prop: 'ipqcTimeframeId',
            type: 'select',
            props: {
              label: 'label',
              value: 'id'
            },
            span: 8,
            dicUrl: '/api/mes-product/qms-ipqc-timeframe/list',
            dicFormatter: (data) => {
              return data.data.map((item) => ({
                ...item,
                label: `${item.startTime}-${item.endTime}`
              }));
            },
            rules: [{ required: true, message: '请选择巡检时段', trigger: 'change' }]
            // addDisplay: false,
            // editDisplay: false
          },
          {
            label: '备注',
            prop: 'remark',
            span: 24,
            type: 'textarea'
          }
        ]
      },
      localData: [] // 本地表格数据备份
    };
  },
  computed: {
    permissionList() {
      return {
        editBtn: this.dialogType === 'add'
      };
    }
  },
  methods: {
    async getDetail(id) {
      try {
        const res = await getPlanConfigDetail({ id: id });
        const data = res.data.data;
        const options = JSON.parse(data.options);
        delete data.options;
        const sendExamineType = data.sendExamineType ? data.sendExamineType.split(',') : [];
        this.form = {
          ...data,
          ...options,
          sendExamineType
        };
      } catch (e) {
        console.warn(e);
      }
    },
    handleEditReset() {
      this.$refs.editForm.resetForm();
      this.form = {
        planType: '制程巡检'
      };
      this.$emit('update:visible', false);
      this.$emit('closeDialog');
    },
    handleEditSubmit() {
      this.$refs.editForm.submit();
    },
    beforeOpen(done, type) {
      const inspectSubType = this.form.inspectSubType;
      if (!inspectSubType) {
        this.$message.warning('请选择巡检类型');
        return;
      }
      this.curdForm.inspectSubType = inspectSubType;
      // const workShopRules = [{ required: true, message: '请选择车间', trigger: 'blur' }];
      // const lineRules = [{ required: true, message: '请选择产线', trigger: 'blur' }];
      // const column = this._cloneDeep(this.tableOption.column);
      // if (inspectSubType === 'WORKSHOP') {
      //   column[1].rules = workShopRules;
      //   column[2].rules = [];
      // } else if (inspectSubType === 'LINE') {
      //   column[1].rules = [];
      //   column[2].rules = lineRules;
      // }
      done();
    },
    judgeIsRepeat(qmsInspectionPlanObjectVOList, selectData) {
      let isRepeat = false;
      let reuslt = [];
      if (this.form.inspectSubType === 'LINE') {
        const map = {};
        for (let qmsInspectionPlanObjectVO of qmsInspectionPlanObjectVOList) {
          map[qmsInspectionPlanObjectVO.lineId] = qmsInspectionPlanObjectVO.ipqcTimeframeId;
        }
        for (let record of selectData) {
          // lineId 和 ipqcTimeframeId 都相等
          if (map[record.lineId] === record.ipqcTimeframeId) {
            isRepeat = true;
            reuslt.push(record.lineName);
          }
        }
      } else if (this.form.inspectSubType === 'WORKSHOP') {
        const map = {};
        for (let qmsInspectionPlanObjectVO of qmsInspectionPlanObjectVOList) {
          map[qmsInspectionPlanObjectVO.workshopId] = qmsInspectionPlanObjectVO.ipqcTimeframeId;
        }
        for (let record of selectData) {
          // lineId 和 ipqcTimeframeId 都相等
          if (map[record.workshopId] === record.ipqcTimeframeId) {
            isRepeat = true;
            reuslt.push(record.workshopName);
          }
        }
      }
      return { isRepeat, reuslt };
    },
    async handSaveConfig(form, done) {
      if (!this.form.qmsInspectionPlanObjectVOList || !this.form.qmsInspectionPlanObjectVOList.length) {
        this.$message.error('请选择巡检对象');
        done();
        return;
      }
      try {
        const formData = filterEmptyValues(this._cloneDeep(this.form));
        const options = {
          missingInspectControl: formData.missingInspectControl,
          closeInspectDuration: formData.closeInspectDuration
        };
        const params = {
          id: formData.id,
          options: JSON.stringify(options),
          inspectType: 'IPQC',
          inspectSubType: formData.inspectSubType,
          planNo: formData.planNo || '',
          planName: formData.planName,
          sendExamineType: formData.sendExamineType.join(','),
          qmsInspectionPlanObjectVOList: formData.qmsInspectionPlanObjectVOList
        };
        const res = await savePlanConfig(params);
        this.$message.success('保存成功');
        this.$refs.editForm.resetForm();
        this.$emit('update:visible', false);
        this.$emit('closeDialog');
      } catch (e) {
        console.log(e);
      } finally {
        done();
      }
    },
    rowSave(row, done, loading) {
      try {
        const { inspectSubType, ipqcTimeframeId, remark, $ipqcTimeframeId } = row;
        const qmsInspectionPlanObjectVOList = this._cloneDeep(this.form.qmsInspectionPlanObjectVOList) || [];
        const selectData = this.selectRow.map((item) => {
          let obj = { inspectSubType, ipqcTimeframeId, remark, ipqcTimeframe: $ipqcTimeframeId };
          if (inspectSubType === 'LINE') {
            obj.lineId = item.id;
            obj.lineName = item.name;
            if (row.workshopId) {
              obj.workshopId = row.workshopId;
              obj.workshopName = row.workshopName;
            }
          } else if (inspectSubType === 'WORKSHOP') {
            obj.workshopId = item.id;
            obj.workshopName = item.name;
          }
          return obj;
        });
        const { isRepeat, reuslt } = this.judgeIsRepeat(qmsInspectionPlanObjectVOList, selectData);
        if (qmsInspectionPlanObjectVOList.length && isRepeat) {
          let msg = '';
          msg += `<p class='confirm-message-wrap'>以下产线已存在一条计划，请先将原计划的产品去掉后再重新配置该计划！</p>
</br>${this.form.inspectSubType === 'LINE' ? '产线' : '车间'}名称:${reuslt.toString()}`;
          this.$confirm(`${msg}`, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString: true,
            type: 'warning'
          }).then(() => {});
        } else {
          qmsInspectionPlanObjectVOList.push(...selectData);
          this.$set(this.form, 'qmsInspectionPlanObjectVOList', qmsInspectionPlanObjectVOList);
          this.selectRow = [];
          this.curdForm = {};
        }
        done();
      } catch (e) {
        console.log(e);
      }
    },
    rowUpdate(row, index, done, loading) {
      const { inspectSubType, ipqcTimeframeId, remark, $ipqcTimeframeId } = row;
      const qmsInspectionPlanObjectVOList = this._cloneDeep(this.form.qmsInspectionPlanObjectVOList) || [];
      qmsInspectionPlanObjectVOList.splice(index, 1);
      const selectData = this.selectRow.map((item) => {
        let obj = { inspectSubType, ipqcTimeframeId, remark, ipqcTimeframe: $ipqcTimeframeId };
        if (inspectSubType === 'LINE') {
          obj.lineId = item.id;
          obj.lineName = item.name;
          if (row.workshopId) {
            obj.workshopId = item.workshopId;
            obj.workshopName = item.workshopName;
          }
        } else if (inspectSubType === 'WORKSHOP') {
          obj.workshopId = item.id;
          obj.workshopName = item.name;
        }
        return obj;
      });
      const { isRepeat, reuslt } = this.judgeIsRepeat(qmsInspectionPlanObjectVOList, selectData);
      if (qmsInspectionPlanObjectVOList.length && isRepeat) {
        let msg = '';
        msg += `<p class='confirm-message-wrap'>以下产线已存在一条计划，请先将原计划的产品去掉后再重新配置该计划！</p>
</br>${this.form.inspectSubType === 'LINE' ? '产线' : '车间'}名称:${reuslt.toString()}`;
        this.$confirm(`${msg}`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {});
      } else {
        qmsInspectionPlanObjectVOList.push(...selectData);
        this.$set(this.form, 'qmsInspectionPlanObjectVOList', qmsInspectionPlanObjectVOList);
        this.selectRow = [];
        this.curdForm = {};
      }
      //this.isFirstInit = true;
      done();
    },
    rowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.form.qmsInspectionPlanObjectVOList.splice(index, 1);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    searchReset() {
      this.query = {};
      this.handleSearch();
    },
    searchChange(params, done) {
      this.query = params;
      this.handleSearch();
      done();
    },
    handleSearch() {},
    openWorkshop() {
      this.modalName = 'workshop';
      this.$refs.commonModalTemplate.showModal();
      this.modal;
      this.dialogOption = {
        modalTitle: '选择车间（双击进行选择）',
        url: '/api/mes-product/qms-inspection-planconfig/query-page-ipqc-unUsed-workshopVO',
        isPage: true,
        rowSelectionType: this.curdForm.inspectSubType === 'LINE' ? 'single' : '',
        columnDefs: [
          {
            label: '车间名称',
            prop: 'name',
            search: true
          },
          {
            label: '车间编码',
            prop: 'code'
          }
        ]
      };
    },
    openProductionLine() {
      this.modalName = 'productionLine';
      this.$refs.commonModalTemplate.showModal();
      this.dialogOption = {
        modalTitle: '选择产线（双击进行选择）',
        url: '/api/mes-product/qms-inspection-planconfig/query-page-ipqc-unUsed-productionLineVO',
        isPage: true,
        method: 'post',
        isRequestor: true,
        query: {
          workShopIdList: (this.curdForm.workshopId && this.curdForm.workshopId.split(',')) || []
        },
        columnDefs: [
          {
            label: '产线名称',
            prop: 'name',
            search: true
          },
          {
            label: '产线编码',
            prop: 'code'
          }
        ]
      };
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workshop':
          if (Array.isArray(rowData)) {
            this.curdForm.workshopId = rowData.map((item) => item.id).join(',');
            this.curdForm.workshopName = rowData.map((item) => item.name).join(',');
            this.selectRow = rowData;
          } else {
            this.curdForm.workshopId = rowData.id || '';
            this.curdForm.workshopName = rowData.name || '';
          }
          break;
        case 'productionLine':
          this.curdForm.lineId = rowData.map((item) => item.id).join(',');
          this.curdForm.lineName = rowData.map((item) => item.name).join(',');
          this.selectRow = rowData;
          break;
        default:
          break;
      }
    }
  }
};
</script>

<style scoped lang="scss">
.dialog-content {
  height: calc(100vh - 180px);
  overflow-y: scroll;
  h3 {
    margin: 0;
    font-size: 14px;
  }
  .mt20 {
    margin-top: 20px;
  }
  .ml20 {
    margin-left: 20px;
  }
  .rules-container {
    display: flex;
    align-items: center;
    height: 32px;
  }
  .num-input-contain {
    color: #606266;
  }
  .input-width {
    width: 300px;
  }
}
label {
  font-size: 14px;
  margin-left: 16px;
  color: #606266;
}

.dialog-footer {
  height: 52px;
  text-align: right;
  padding: 20px;
}
.confirm-message-wrap {
  word-wrap: break-word;
}
</style>
